
package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.List;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Bed;
import com.lmx.repoDomain.tmodel.Building;
import com.lmx.repoDomain.tmodel.Device;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.Floor;
import com.lmx.repoDomain.tmodel.Room;
import com.lmx.repoDomain.tmodel.Tenant;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * 
 * 
 * @author huibati
 * @version 1.00
 */
@Service
@Scope("prototype")
public class JsonModelService<T> {

	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;

	@Autowired
	protected GenericService dslJpaService;

	@Autowired
	protected CommonService commonService;

	@Autowired
	private WorkPlaceService workPlaceService;

	@Autowired
	private DeviceService deviceService;

	// 批量生成 room 以及beds
	@Transactional
	public String createRoomsBeds(String jsonData) {
		// jsonData="{\"flag\":\"edit\",\"minSeq\":\"104\",\"maxSeq\":\"104\",\"room\":{\"roomId\":\"284\",\"delFlag\":0,\"remark\":\"一楼房间\",\"area\":35,\"roomType\":\"roomTypeSpecial\",\"orientation\":\"83\",\"build\":\"121\",\"floor\":\"36576\",\"toilet\":\"true\",\"balcony\":false,\"scanner\":\"0\",\"bedNum\":3},\"beds\":[{\"bedId\":\"102\",\"name\":\"1\",\"bedType\":\"116\",\"price\":\"100\",\"delFlag\":0,\"button\":\"0\"},{\"bedId\":\"103\",\"name\":\"2\",\"bedType\":\"117\",\"price\":\"150\",\"delFlag\":0,\"button\":\"0\"},{\"name\":\"5\",\"bedType\":\"116\",\"price\":\"200\",\"delFlag\":0,\"button\":\"0\"},{\"bedId\":\"477\",\"name\":\"3\",\"bedType\":\"116\",\"price\":\"333\",\"delFlag\":1}]}";
		// jsonData="{\"flag\":\"edit\",\"minSeq\":\"104\",\"maxSeq\":\"104\",\"room\":{\"roomId\":\"284\",\"remark\":\"一楼房间\",\"area\":35,\"roomType\":\"roomTypeSpecial\",\"orientation\":\"83\",\"build\":\"121\",\"floor\":\"36576\",\"toilet\":\"true\",\"balcony\":false,\"scanner\":\"0\",\"bedNum\":3,\"delFlag\":1},\"beds\":[]}";
		// JSONArray jsonArray = JSONArray.fromObject("["+jsonData+"]");
		JSONArray jsonArray = JSONArray.fromObject(jsonData);
		JSONObject jsonObject = jsonArray.getJSONObject(0);
		List<Room> roomUpdateList = new ArrayList<>();
		List<Room> roomInsertList = new ArrayList<>();
		List<Bed> bedUpdateList = new ArrayList<>();
		List<Bed> bedInsertList = new ArrayList<>();
		List<Device> deviceOldList = new ArrayList<>();// 原有设备状态置为空闲
		List<Device> deviceNewList = new ArrayList<>();// 新添加的设备 状态置为占用
		List<Device> deviceDelList = new ArrayList<>();// 删除的 的设备 状态置为空闲
		String minSeq = jsonObject.getString("minSeq");// 编号最小值
		String maxSeq = jsonObject.getString("maxSeq");// 编号最大值
		String updateFlag = jsonObject.getString("flag");// 标识 增添or编辑room
		JSONObject roomJson = jsonObject.getJSONObject("room");
		JSONArray beds = jsonObject.getJSONArray("beds");
		int roomNum = 0;
		int roomNumFlag = 0;
		int roomNumFlagAdd = 0;// 房屋增添 房屋数
		int roomNumFlagEdit = 0;// 房屋编辑 房屋数
		Tenant tenant = new Tenant();
		tenant.setId(ActionContextHolder.getContext().getTenantId());
		roomNum = Integer.parseInt(maxSeq) - Integer.parseInt(minSeq) + 1;// 房间数
		if ("add".equals(updateFlag)) {// 新增房间
			if (roomNum == 0) {
				roomNum = 1;
			}
			roomNumFlagAdd = roomNum;
		}
		if ("edit".equals(updateFlag)) {// 编辑房间
			roomNumFlagEdit = 0;
		}
		Building parBuilding = workPlaceService.getBuildingById(roomJson.getLong("build"));
		int bRoomNum = 0;// 楼宇相应房间数
		if (parBuilding.getRoomNum() != null) {
			bRoomNum = parBuilding.getRoomNum();
		}
		Floor parFloor = workPlaceService.getFloorById(roomJson.getLong("floor"));
		int fRoomNum = 0;// 楼层相应房间数
		if (parFloor.getRoomNum() != null) {
			fRoomNum = parFloor.getRoomNum();
		}
		List<String> roomNameList = workPlaceService.getRoomNameByFloor(parFloor);// 所选楼层所有房屋名称
		// "remark":"12","area":"111","roomType":"3","build":"98","floor":"35132","toilet":true,"balcony":true,"bedNum":2
		// 根据json数据初始化room数据
		Room room = new Room();
		Device scannerTemp = null;
		if (roomJson.get("roomId") != null) {// Room存在id
			room.setId(Long.parseLong(roomJson.getString("roomId")));
			room = workPlaceService.getRoom(room);
			if (room != null && room.getScanner() != null) {
				scannerTemp = room.getScanner();
				room.setScanner(deviceService.getDeviceWithId(room.getScanner().getId()));
				// 置为空闲
				room.getScanner().setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_STATUS_1.label()));
				room.getScanner().setBindStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_2.label()));
				deviceOldList.add(room.getScanner());
			}
		}
		room.setFloor(parFloor);
		room.setArea(roomJson.getString("area"));
		room.setBedNum(roomJson.getInt("bedNum"));
		if (roomJson.get("remark") != null) {
			room.setRemark(roomJson.getString("remark"));
		}
		if (roomJson.containsKey("roomType") && roomJson.get("roomType") != null
				&& !"0".equals(roomJson.getString("roomType"))) {// 房屋类型
			room.setRoomType(commonService.getDicttype(roomJson.getString("roomType")));
		}
		if (roomJson.containsKey("orientation") && roomJson.get("orientation") != null
				&& roomJson.getLong("orientation") != 0) {// 房屋朝向
			Dicttype orientation = new Dicttype();
			orientation.setId(roomJson.getLong("orientation"));
			room.setOrientation(orientation);
		}
		if (roomJson.containsKey("scanner") && roomJson.get("scanner") != null && roomJson.getLong("scanner") != 0) {
			Device scanner = deviceService.getDeviceWithId(roomJson.getLong("scanner"));
			if (scanner != null) {// 验证所填设备被占用
				if (scannerTemp == null || (!scannerTemp.getId().equals(scanner.getId()))) {
					if ((scanner.getBindStatus() != null && CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_1.label().equals(scanner.getBindStatus().getTypecode()))
							|| (scanner.getStatus() != null
									&& CommonConstants.DICTTYPE.DEVICE_STATUS_2.label().equals(scanner.getStatus().getTypecode()))) {
						return scanner.getSeq();
					}
				}
				room.setScanner(scanner);
				// 状态改为占用
				scanner.setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_STATUS_2.label()));
				scanner.setBindStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_1.label()));
				deviceNewList.add(scanner);
			}
		}
		if (roomJson.containsKey("delFlag")) {// 删除标识
			if ("1".equals(roomJson.getString("delFlag"))) {
				room.setDelStatus((short) 1);
				roomNumFlagEdit = -1;// 删除标识 删除此Room
				if (room.getScanner() != null) {
					// 状态改为空闲
					room.getScanner().setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_STATUS_1.label()));
					room.getScanner().setBindStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_2.label()));
					deviceDelList.add(room.getScanner());
				}
			}
		} else {
			room.setDelStatus((short) 0);
		}

		if ("true".equals(roomJson.getString("toilet"))) {
			room.setToilet("true");
		} else {
			room.setToilet(null);
		}
		if ("true".equals(roomJson.getString("balcony"))) {
			room.setBalcony("true");
		} else {
			room.setBalcony(null);
		}
		// {"name":"111","bedType":"1","price":"123","remark":"122"}
		// 根据json数据 初始化bed数据
		List<Bed> bedList = new ArrayList<>();
		for (int i = 0; i < beds.size(); i++) {
			JSONObject jsonObjectTemp = beds.getJSONObject(i);
			Bed bedTemp = new Bed();
			Device buttonTemp = null;
			if (jsonObjectTemp.get("bedId") != null) {
				bedTemp.setId(Long.parseLong(jsonObjectTemp.getString("bedId")));
				bedTemp = workPlaceService.getBed(bedTemp);
				if (bedTemp != null && bedTemp.getButton() != null) {
					buttonTemp = bedTemp.getButton();
					// 状态改为空闲
					bedTemp.getButton().setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_STATUS_1.label()));
					bedTemp.getButton().setBindStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_2.label()));
					deviceOldList.add(bedTemp.getButton());
				}
			}
			if (bedTemp != null) {
				bedTemp.setName(jsonObjectTemp.getString("name"));
				bedTemp.setPrice(jsonObjectTemp.getString("price"));
				if(jsonObjectTemp.containsKey("totalPrice")){
					bedTemp.setTotalPrice(jsonObjectTemp.getString("totalPrice"));
				}
				if (jsonObjectTemp.get("remark") != null) {
					bedTemp.setRemark(jsonObjectTemp.getString("remark"));
				}
				bedTemp.setDelStatus(Short.valueOf(jsonObjectTemp.getString("delFlag")));
				if (jsonObjectTemp.containsKey("bedType") && jsonObjectTemp.get("bedType") != null
						&& jsonObjectTemp.getLong("bedType") != 0) {
					Dicttype bedType = new Dicttype();
					bedType.setId(jsonObjectTemp.getLong("bedType"));
					bedTemp.setBedType(bedType);
				}
				if (jsonObjectTemp.containsKey("button") && jsonObjectTemp.get("button") != null
						&& !"0".equals(jsonObjectTemp.getString("button"))) {
					Device button = deviceService.getDeviceWithId(Long.parseLong(jsonObjectTemp.getString("button"))); // 修改设备状态用
					if (button != null) {// 验证所填设备被占用
						if (buttonTemp == null || (!buttonTemp.getId().equals(button.getId()))) {
							if ((button.getBindStatus() != null
									&& CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_1.label().equals(button.getBindStatus().getTypecode()))
									|| (button.getStatus() != null
											&& CommonConstants.DICTTYPE.DEVICE_STATUS_2.label().equals(button.getStatus().getTypecode()))) {
								return button.getSeq();
							}
						}
						bedTemp.setButton(button);
						// 状态改为占用
						button.setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_STATUS_2.label()));
						button.setBindStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_1.label()));
						deviceNewList.add(button);
					}
				}
			}
			bedList.add(bedTemp);
		}
		// 保存房屋以及床位信息
		for (int k = 0; k < roomNum; k++) {
			if ("add".equals(updateFlag) && roomNameList.contains(String.valueOf(Integer.parseInt(minSeq) + k))) {// 该楼层已存在同名的房屋不创建
				roomNumFlagAdd--;
			} else {
				// 保存房屋 属性值复制
				Room room2 = new Room();
				BeanUtils.copyProperties(room, room2);
				if (room.getId() != null) {
					room2.setId(room.getId());
					// room2=workPlaceService.getRoom(room2);
				}
				if (room.getRoomType() != null) {
					room2.setRoomType(room.getRoomType());
				}
				if (room.getOrientation() != null) {
					room2.setOrientation(room.getOrientation());
				}
				if (room.getScanner() != null) {
					room2.setScanner(room.getScanner());
				}
				room2.setName(String.valueOf(Integer.parseInt(minSeq) + k));
				room2.setDelStatus((short) 0);
				room2.setTenant(tenant);
				if (room2.getId() == null) {
					room2.setCreateDateTime(CommonUtil.getCurrTimes());
					roomInsertList.add(room2);
				} else {
					room2.setLastUpdateDateTime(CommonUtil.getCurrTimes());
					roomUpdateList.add(room2);
				}
				// 批量产生床位
				if (bedList.size() > 0) {
					// List<Bed> bedListTemp = new ArrayList<>();
					for (int i = 0; i < bedList.size(); i++) {
						if (bedList.get(i) != null) {
							// 属性值复制
							Bed temp = new Bed();
							if (bedList.get(i).getId() != null) {
								temp.setId(bedList.get(i).getId());
								temp = workPlaceService.getBed(temp);
							}
							if (temp != null) {
								BeanUtils.copyProperties(bedList.get(i), temp);
								temp.setBedType(bedList.get(i).getBedType());
								temp.setRoom(room2);
								temp.setTenant(room2.getTenant());
								if (bedList.get(i).getDelStatus() == 1) {
									temp.setDelStatus((short) 1);
									// 设备置为空闲
									if (temp.getButton() != null) {
										temp.getButton().setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_STATUS_1.label()));
										temp.getButton().setBindStatus(commonService.getDicttype(CommonConstants.DICTTYPE.DEVICE_BIND_STATUS_2.label()));
										deviceDelList.add(temp.getButton());
									}
								} else {
									temp.setDelStatus((short) 0);
								}
								if (temp.getId() != null) {
									temp.setLastUpdateDateTime(CommonUtil.getCurrTimes());
									bedUpdateList.add(temp);
								} else {
									temp.setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.BED_STATUS_1.label()));
									temp.setCreateDateTime(CommonUtil.getCurrTimes());
									bedInsertList.add(temp);
								}
							}
						}
					}
					//
				}
			}
		}
		if (roomInsertList.size() > 0) {
			commonService.batchInsert(roomInsertList);// 新增room
		}
		if (roomUpdateList.size() > 0) {
			commonService.batchUpdate(roomUpdateList);// 更新room
		}
		if (bedInsertList.size() > 0) {
			commonService.batchInsert(bedInsertList); // 批量添加bed
		}
		if (bedUpdateList.size() > 0) {
			commonService.batchUpdate(bedUpdateList); // 更新bed
		}
		if (deviceOldList.size() > 0) {
			commonService.batchUpdate(deviceOldList); // 将原有的设备--空闲
		}
		if (deviceNewList.size() > 0) {
			commonService.batchUpdate(deviceNewList); // 将新增/编辑的设备--占用
		}
		if (deviceDelList.size() > 0) {
			commonService.batchUpdate(deviceDelList); // 将删除的设备--空闲
		}
		if ("add".equals(updateFlag)) {
			roomNumFlag = roomNumFlagAdd;
		}
		if ("edit".equals(updateFlag)) {
			roomNumFlag = roomNumFlagEdit;
		}
		// 更改楼层 房屋数
		parFloor.setRoomNum(fRoomNum + roomNumFlag);
		dslJpaService.setEntityClass(Floor.class);
		dslJpaService.update(parFloor);
		// 更改楼宇房屋数
		parBuilding.setRoomNum(bRoomNum + roomNumFlag);
		dslJpaService.setEntityClass(Building.class);
		dslJpaService.update(parBuilding);
		return "1";
	}
}
